import React, { useEffect, useState } from 'react';
import {
    Form,
    Input,
    DatePicker,
    InputNumber,
    Cascader,
    Select,
    Row,
    Col,
    Checkbox,
    Button,
    AutoComplete,
} from 'antd';
// 按钮
// import React, { useState } from 'react';
import { useNavigate } from 'react-router';
import { Radio } from 'antd';
import type { RadioChangeEvent } from 'antd';
// 文件上传
// import React, { useState } from 'react';
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import '../../static/css/visitors/add.css'
import { Space } from 'antd';
import adds from '../../apis/visitors/add'
import { cascade } from '../../apis/visitors/cascade'
import type { DatePickerProps, RangePickerProps } from 'antd/es/date-picker';
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

const beforeUpload1 = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};
const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};
const { Option } = Select;
// 设置表单距离
const formItemLayout = {
    labelCol: {
        xs: { span: 10 },
        sm: { span: 7 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 0 },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};


const onOk = (value: DatePickerProps['value'] | RangePickerProps['value']) => {
    // console.log('onOk: ', value);
};
const Add: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const [params, setP] = useState({})
    const [time, setTime] = useState<any>({ k: '', j: '' })
    const [department,setDepartment]=useState<any>('')

    const onFinish = (values: any) => {
        // console.log(values);
        
        const _add = { ...values, starttime: time.k, endtime: time.j ,department}
        adr(_add)
    };
    // 添加接口
    const navigate = useNavigate()
    const adr = async (_add: any) => {
        const res = await adds(_add)
        // console.log(res)
        // if(res.code==='00000'){
            message.success('添加成功', 2);
            navigate('/table/list')
        // }else{
        //     message.error(res.msg, 2);
        // }
    }
    // 日期选择器
    const ange = (
        value: DatePickerProps['value'] | RangePickerProps['value'],
        dateString: [string, string] | string,
    ) => {
        setTime({ ...time, k: dateString })

    };
    // 离校
    const ge = (
        value: DatePickerProps['value'] | RangePickerProps['value'],
        dateString: [string, string] | string,
    ) => {
        setTime({ ...time, j: dateString })

    };
    const handleChange1: UploadProps['onChange'] = (info: any) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            console.log(info.file);
            
            // getBase64(info.file.originFileObj as RcFile, url => {
                // setLoading(false);
                // setImageUrl(infofile);
            // });
        }
    };
    const handleChange: UploadProps['onChange'] = (info: any) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            console.log(info.file);
            
            // getBase64(info.file.originFileObj as RcFile, url => {
                // setLoading(false);
                // setImageUrl(infofile);
            // });
        }
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const [form] = Form.useForm();
    const onFill = () => {
        form.setFieldsValue({
            note: 'Hello world!',
            gender: 'male',
        });
    };
    // 级联
    const [options,setOption] = useState()
    const nge: any = (value: string[]) => {
        setDepartment(value.slice(-1)[0])
    };
    const fieldNames = { label: 'name', value: 'id', children: 'son' }

    const ww = async () => {
       const res:any = await cascade()
    //    console.log(res)
       setOption(res.data)
    }
    useEffect(()=>{
        ww()
    })
    const Authorization:any=sessionStorage.getItem('token')
    return (
        <div style={{ padding: '10px', backgroundColor: '#fff' }}>
            <h1>添加</h1>
            <Form
                {...formItemLayout}
                form={form}
                name="register"
                onFinish={onFinish}
                scrollToFirstError
            >
                <Row>
                    <Col span={10}>
                        {/* 类型 */}
                        <Form.Item
                            name="type"
                            label="类型"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入访客名称',
                                },
                            ]}
                        >
                            <Radio.Group name="status">
                                <Radio value={1} checked={true} >外来人员</Radio>
                                <Radio value={2}>老师</Radio>
                                <Radio value={3}>学生</Radio>

                            </Radio.Group>
                        </Form.Item>
                        {/* 访客名称 */}
                        <Form.Item
                            name="username"
                            label="访客名称"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入访客名称',
                                },
                            ]}
                        >
                            <Input placeholder="请输入访客名称" />
                        </Form.Item>
                        {/* 手机号 */}
                        <Form.Item
                            name="mobile"
                            label="手机号"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入手机号',
                                },
                            ]}
                        >
                            <Input placeholder="请输入手机号" />
                        </Form.Item>
                        {/* openid */}
                        <Form.Item
                            name="openid"
                            label="openid"
                            rules={[
                                {
                                    required: true,
                                    message: 'openid',
                                },
                            ]}
                        >
                            <Input placeholder="openid" />
                        </Form.Item>
                        {/* 身份证号 */}
                        <Form.Item
                            name="card"
                            label="身份证号"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入身份证号',
                                },
                            ]}
                        >
                            <Input placeholder="请输入身份证号" />
                        </Form.Item>
                        {/* 车牌号 */}
                        <Form.Item
                            name="carnumber"
                            label="车牌号"
                        >
                            <Input placeholder="请输入车牌号" />
                        </Form.Item>
                        {/* 理由 */}
                        <Form.Item
                            name="reason"

                            label="理由"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入访客理由',
                                },
                            ]}
                        >
                            <Input placeholder="请输入理由" />
                        </Form.Item>
                        {/* 部门 */}
                        <Form.Item
                            name="department"
                            label="部门"
                        >
                            <Cascader placeholder='请选择' fieldNames={fieldNames}  options={options} onChange={nge} />
                            {/*  */}
                        </Form.Item>
                        {/* 进校时间 */}
                        <Form.Item
                            name="starttime"
                            label="进校时间"
                            rules={[{ required: true, message: '进校时间' }]}
                        >
                            <DatePicker showTime onChange={ange} onOk={onOk} />
                        </Form.Item>
                        {/* 离校时间 */}
                        <Form.Item
                            name="endtime"
                            label="离校时间"
                            rules={[{ required: true, message: '离校时间' }]}
                        >
                            <DatePicker showTime onChange={ge} onOk={onOk} />
                        </Form.Item>
                        {/* 是否去过高风险区 */}
                        <Form.Item

                            label="是否去过高风险地区"

                        >
                            <Radio.Group name="radiogroup" >
                                <Radio value={1} >否</Radio>
                                <Radio value={2}>是</Radio>
                            </Radio.Group>


                        </Form.Item>
                        {/* 是否接触过高风险区 */}
                        <Form.Item

                            label="是否接触过高风险区"

                        >
                            <Radio.Group name="radiogroup">
                                <Radio value={1}>否</Radio>
                                <Radio value={2}>是</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {/* 是否离京 */}
                        <Form.Item

                            label="是否离京"

                        >
                            <Radio.Group name="radiogroup" >
                                <Radio value={1}>否</Radio>
                                <Radio value={2}>是</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {/* 健康状态 */}
                        <Form.Item
                            label="健康状态"

                        >
                            <Radio.Group name="radiogroup">
                                <Radio value={1}>良好</Radio>
                                <Radio value={2}>一般</Radio>
                                <Radio value={3}>差</Radio>
                            </Radio.Group>
                        </Form.Item>


                    </Col>
                    {/* 上传所需要的图片 */}
                    <Col span={14}>
                        <div className='colImg'>
                            <div>
                                <Form.Item name="aaa"
                                    label="行程码"
                                    // 以下两条是必须的
                                    //  valuePropName="fileList" 
                                    //  // 如果没有下面这一句会报错
                                    //  getValueFromEvent={normFile} 
                                    labelCol={{ span: 10, offset: 300 }}>
                                    <Upload
                                        headers={{Authorization}}
                                        name="file"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        // className = ''
                                        showUploadList={false}
                                        action="http://121.42.230.80/api/visit/upload"
                                        beforeUpload={beforeUpload1}
                                        onChange={handleChange1}
                                    >
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                    </Upload>
                                </Form.Item>
                            </div>
                            <div className='colDiv'>
                                <Form.Item name="username"
                                    label="疫苗"
                                    labelCol={{ span: 10, offset: 300 }}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请上传疫苗',
                                        },
                                    ]}>
                                    <Upload
                                        name="avatar"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        // className = ''
                                        showUploadList={false}
                                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                        beforeUpload={beforeUpload}
                                        onChange={handleChange}
                                    >
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                    </Upload>
                                </Form.Item>
                            </div>
                        </div>
                        <div className='colImg'>
                            <div>
                                <Form.Item name="username"
                                    label="健康码"
                                    labelCol={{ span: 10, offset: 300 }}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请上传健康码',
                                        },
                                    ]}>
                                    <Upload
                                        name="avatar"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        // className = ''
                                        showUploadList={false}
                                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                        beforeUpload={beforeUpload}
                                        onChange={handleChange}
                                    >
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                    </Upload>
                                </Form.Item>
                            </div>
                            <div className='colDiv'>
                                <Form.Item name="username"
                                    label="核酸"
                                    labelCol={{ span: 10, offset: 300 }}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请上传核酸',
                                        },
                                    ]}>
                                    <Upload
                                        name="avatar"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        // className = ''
                                        showUploadList={false}
                                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                        beforeUpload={beforeUpload}
                                        onChange={handleChange}
                                    >
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                    </Upload>
                                </Form.Item>
                            </div>
                        </div>
                        <Form.Item {...tailFormItemLayout} style={{ marginTop: '280px' }}>
                            <Button type="link" htmlType="button" onClick={onFill} style={{ border: '1px solid #eee', marginRight: '10px' }}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确认
                            </Button>

                        </Form.Item>
                    </Col>

                </Row>
            </Form>



        </div>
    );
};

export default Add;